package core

import (
	"strconv"
	"go-iot/app/common/logger"
)

// 设备
type Device struct {
	Id         string            `json:"id"`
	ProductId  string            `json:"productId"`
	ParentId   string            `json:"parentId"`
	DeviceType string            `json:"devType"`
	ClusterId  string            `json:"clusterId"` // 所在集群id
	CreateId   int64             `json:"-"`
	Config     map[string]string `json:"-"`
	Name       string            `json:"name"`
}

func NewDevice(devieId string, productId string, createId int64) *Device {
	return &Device{
		Id:        devieId,
		ProductId: productId,
		CreateId:  createId,
		Config:    make(map[string]string),
	}
}

func (d *Device) GetId() string {
	return d.Id
}
func (d *Device) GetProductId() string {
	return d.ProductId
}
func (d *Device) GetCreateId() int64 {
	return d.CreateId
}
func (d *Device) GetSession() Session {
	s := GetSession(d.Id)
	return s
}

// 获取临时数据
func (d *Device) GetData(key string) string {
	return GetDeviceData(d.Id, key)
}

// 获取设备临时数据int
func (d *Device) GetDataInt(key string) int {
	i, err := strconv.ParseInt(GetDeviceData(d.Id, key), 10, 64)
	if err != nil {
		logger.Errorf("device [%s] GetDataInt error: %v", d.Id, err)
	}
	return int(i)
}

// 设置临时数据
func (d *Device) SetData(key string, val string) {
	SetDeviceData(d.Id, key, val)
}

func (d *Device) GetConfig(key string) string {
	if v, ok := d.Config[key]; ok {
		return v
	}
	p := GetProduct(d.ProductId)
	if p != nil {
		v := p.GetConfig(key)
		return v
	}
	return ""
}

// 设置设备配置
func (d *Device) SetConfig(key string, value string) {
	d.Config[key] = value
}

// 是否子设备
func (d *Device) IsSubDevice() bool {
	return d.DeviceType == SUBDEVICE
}
